import React, { useState } from 'react';
import { View, StyleSheet, Text, Image, TouchableOpacity, FlatList, TextInput, Animated, Dimensions, PanResponder } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { Ionicons } from '@expo/vector-icons';
import { BottomTabNavigationProp } from '@react-navigation/bottom-tabs';
import DefaultAvatar from '@/assets/images/default_avatar.png';

type TabParamList = {
  index: undefined;
  chat: undefined;
  square: undefined;
  my: undefined;
  chatScreen: { userId: string };
  friends: undefined;
  interaction: undefined;
  comments: undefined;
  application: undefined;
  footprint: undefined;
  seen: undefined;
  like_me: undefined;
};

// 定义系统消息类型
interface SystemMessage {
  id: string;
  type: 'system';
  icon: string;
  title: string;
  description: string;
  url: keyof TabParamList;
}

// 定义聊天消息类型
interface ChatMessage {
  id: string;
  avatar: string;
  name: string;
  lastMessage: string;
  time: string;
  unread: number;
}

// 系统消息数据
const SYSTEM_MESSAGES: SystemMessage[] = [
  {
    id: '1',
    type: 'system',
    icon: 'thumbs-up',
    title: '点赞',
    description: '暂无互动消息~',
    url: 'interaction'
  },
  {
    id: '2',
    type: 'system',
    icon: 'chatbubbles',
    title: '评论',
    description: '暂无互动消息~',
    url: 'comments'
  },
  {
    id: '3',
    type: 'system',
    icon: 'person-add',
    title: '好友申请',
    description: '暂无好友请求~',
    url: 'application'
  },
  {
    id: '4',
    type: 'system',
    icon: 'hand-right',
    title: 'Say hi足迹',
    description: '你还没有向别人打过招呼呢~',
    url: 'footprint'
  },
  {
    id: '5',
    type: 'system',
    icon: 'person',
    title: '谁看过我',
    description: 'shaa 访问了你的主页~',
    url: 'seen'
  },
  {
    id: '6',
    type: 'system',
    icon: 'heart',
    title: '喜欢我',
    description: '暂无喜欢我~',
    url: 'like_me'
  }
];

// 聊天消息数据
const CHAT_MESSAGES: ChatMessage[] = [
  {
    id: '1',
    name: '左左',
    avatar: 'https://ts2.cn.mm.bing.net/th?id=ORMS.d06126240c548af3658f48d1981de3d9&pid=Wdp&w=268&h=140&qlt=90&c=1&rs=1&dpr=1&p=0',
    lastMessage: '今天天气真不错，要不要一起出去玩？',
    time: '3分钟前',
    unread: 2,
  },
  {
    id: '2',
    avatar: 'https://placekitten.com/101/101',
    name: '李四',
    lastMessage: '[图片]',
    time: '10分钟前',
    unread: 0,
  },
  {
    id: '3',
    avatar: 'https://ts1.cn.mm.bing.net/th?id=ORMS.2293845c570c64f281f285660f2a565c&pid=Wdp&w=268&h=140&qlt=90&c=1&rs=1&dpr=1&p=0',
    name: '王五',
    lastMessage: '好的，那就这么说定了！',
    time: '30分钟前',
    unread: 1,
  },
  {
    id: '4',
    name: '宋北',
    avatar: 'https://placekitten.com/101/101',
    lastMessage: '[语音] 10"',
    time: '1小时前',
    unread: 0,
  },
];


const { width } = Dimensions.get('window');

export default function ChatListScreen() {
  const navigation = useNavigation<BottomTabNavigationProp<TabParamList>>();
  const [activeTab, setActiveTab] = useState<'messages' | 'interactions'>('messages');
  const [isSearching, setIsSearching] = useState(false);
  const [searchText, setSearchText] = useState('');
  const slideAnim = React.useRef(new Animated.Value(0)).current;// 控制滑动的动画值
  const [messageTabWidth, setMessageTabWidth] = useState(0);
  const [interactionTabWidth, setInteractionTabWidth] = useState(0);
  const contentSlideAnim = React.useRef(new Animated.Value(0)).current;
  const [errorImages, setErrorImages] = useState<Record<string, boolean>>({});

  // 添加手势处理
  const panResponder = React.useRef(
    PanResponder.create({
      onMoveShouldSetPanResponder: (_, gestureState) => {
        const { dx, dy } = gestureState;
        return Math.abs(dx) > Math.abs(dy * 2) && Math.abs(dx) > 10;
      },
      onPanResponderMove: (_, gestureState) => {
        const { dx } = gestureState;
        const newValue = dx > 0 ? 0 : 1;
        if ((newValue === 0 && activeTab === 'interactions') || 
            (newValue === 1 && activeTab === 'messages')) {
          Animated.spring(slideAnim, {
            toValue: newValue,
            useNativeDriver: true,
            friction: 8,
          }).start();
          Animated.spring(contentSlideAnim, {
            toValue: newValue,
            useNativeDriver: true,
            friction: 8,
          }).start();
        }
      },
      onPanResponderRelease: (_, gestureState) => {
        const { dx } = gestureState;
        if (Math.abs(dx) > width * 0.2) {
          const newTab = dx > 0 ? 'messages' : 'interactions';
          switchTab(newTab);
        } else {
          // 回弹到原位
          Animated.parallel([
            Animated.spring(slideAnim, {
              toValue: activeTab === 'messages' ? 0 : 1,
              useNativeDriver: true,
              friction: 8,
            }),
            Animated.spring(contentSlideAnim, {
              toValue: activeTab === 'messages' ? 0 : 1,
              useNativeDriver: true,
              friction: 8,
            })
          ]).start();
        }
      },
    })
  ).current;

  // 修改切换标签的处理函数
  const switchTab = (tab: 'messages' | 'interactions') => {
    Animated.parallel([
      Animated.spring(slideAnim, {
        toValue: tab === 'messages' ? 0 : 1,
        useNativeDriver: true,
        friction: 8,
      }),
      Animated.spring(contentSlideAnim, {
        toValue: tab === 'messages' ? 0 : 1,
        useNativeDriver: true,
        friction: 8,
      })
    ]).start();
    setActiveTab(tab);
    setIsSearching(false);
  };

  // 修改系统消息渲染函数
  const renderSystemMessage = ({ item }: { item: SystemMessage }) => (
    <TouchableOpacity 
      style={styles.systemItem}
      onPress={() => navigation.navigate(item.url)}
    >
      <View style={styles.iconContainer}>
        <Ionicons 
          name={item.icon as keyof typeof Ionicons.glyphMap} 
          size={24} 
          color="black" 
        />
      </View>
      <View style={styles.messageInfo}>
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.description}>{item.description}</Text>
      </View>
    </TouchableOpacity>
  );

  // 修改聊天消息渲染函数
  const renderChatMessage = ({ item }: { item: ChatMessage }) => (
    <TouchableOpacity 
      style={styles.chatItem}
      onPress={() => navigation.navigate('chatScreen', { userId: item.id })}
    >
      <Image 
        source={errorImages[item.id] ? DefaultAvatar : { uri: item.avatar }}
        style={styles.avatar}
        onError={() => setErrorImages(prev => ({ ...prev, [item.id]: true }))}
      />
      <View style={styles.chatInfo}>
        <View style={styles.topLine}>
          <Text style={styles.name} numberOfLines={1}>{item.name}</Text>
          <Text style={styles.time}>{item.time}</Text>
        </View>
        <View style={styles.bottomLine}>
          <Text style={styles.lastMessage} numberOfLines={1}>
            {item.lastMessage}
          </Text>
          {item.unread > 0 && (
            <View style={styles.unreadBadge}>
              <Text style={styles.unreadText}>
                {item.unread > 99 ? '99+' : item.unread}
              </Text>
            </View>
          )}
        </View>
      </View>
    </TouchableOpacity>
  );

  // 修改渲染顶部导航栏函数
  const renderHeader = () => (
    <>
      <View style={styles.header}>
        {activeTab === 'messages' && (
          <TouchableOpacity 
            style={styles.searchButton}
            onPress={() => setIsSearching(true)}
          >
            <Ionicons name="search" size={24} color="#333" />
          </TouchableOpacity>
        )}

        <View style={[
          styles.tabContainer,
          activeTab === 'interactions' && styles.tabContainerWithoutSearch
        ]}>
          <Animated.View style={[
            styles.tabSlider,
            {
              width: activeTab === 'messages' ? messageTabWidth : interactionTabWidth,
              transform: [{
                translateX: slideAnim.interpolate({
                  inputRange: [0, 1],
                  outputRange: [16,23 + messageTabWidth + 32]
                })
              }]
            }
          ]} />
          <TouchableOpacity 
            style={styles.tab}
            onPress={() => switchTab('messages')}
          >
            <Text 
              style={[styles.tabText, activeTab === 'messages' && styles.activeTabText]}
              onLayout={e => setMessageTabWidth(e.nativeEvent.layout.width)}
            >
              消息
            </Text>
          </TouchableOpacity>
          <TouchableOpacity 
            style={styles.tab}
            onPress={() => switchTab('interactions')}
          >
            <Text 
              style={[styles.tabText, activeTab === 'interactions' && styles.activeTabText]}
              onLayout={e => setInteractionTabWidth(e.nativeEvent.layout.width)}
            >
              互动
            </Text>
          </TouchableOpacity>
        </View>

        <TouchableOpacity 
          style={styles.profileButton}
          onPress={() => navigation.navigate('friends')}
        >
          <Ionicons name="person-circle-outline" size={24} color="#333" />
        </TouchableOpacity>
      </View>

      {isSearching && activeTab === 'messages' && (
        <View style={styles.searchWrapper}>
          <View style={styles.searchContainer}>
            <Ionicons name="search" size={20} color="#999" />
            <TextInput
              style={styles.searchInput}
              placeholder="搜索聊天记录"
              value={searchText}
              onChangeText={setSearchText}
              autoFocus
              returnKeyType="search"
            />
            {searchText.length > 0 && (
              <TouchableOpacity onPress={() => setSearchText('')}>
                <Ionicons name="close-circle" size={16} color="#999" />
              </TouchableOpacity>
            )}
          </View>
          <TouchableOpacity 
            onPress={() => {
              setIsSearching(false);
              setSearchText('');
            }}
          >
            <Text style={styles.cancelButton}>取消</Text>
          </TouchableOpacity>
        </View>
      )}
    </>
  );

  // 添加搜索过滤逻辑
  const filteredData = React.useMemo(() => {
    if (!searchText) {
      return activeTab === 'messages' ? CHAT_MESSAGES : SYSTEM_MESSAGES;
    }
    
    const searchLower = searchText.toLowerCase();
    if (activeTab === 'messages') {
      return CHAT_MESSAGES.filter(item => 
        item.name.toLowerCase().includes(searchLower) ||
        item.lastMessage.toLowerCase().includes(searchLower)
      );
    } else {
      return SYSTEM_MESSAGES.filter(item =>
        item.title.toLowerCase().includes(searchLower) ||
        item.description.toLowerCase().includes(searchLower)
      );
    }
  }, [searchText, activeTab]);

  return (
    <View style={styles.container}>
      {renderHeader()}
      <Animated.View 
        style={styles.contentContainer}
        {...panResponder.panHandlers}
      >
        <Animated.View style={[
          styles.slidingContent,
          {
            transform: [{
              translateX: contentSlideAnim.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -width]
              })
            }]
          }
        ]}>
          <View style={styles.page}>
            {!isSearching ? (
              <FlatList<ChatMessage>
                data={CHAT_MESSAGES}
                renderItem={renderChatMessage}
                keyExtractor={item => item.id}
                style={styles.list}
              />
            ) : searchText ? (
              <FlatList<ChatMessage>
                data={filteredData as ChatMessage[]}
                renderItem={renderChatMessage}
                keyExtractor={item => item.id}
                style={styles.list}
              />
            ) : null}
          </View>
          <View style={styles.page}>
            <FlatList<SystemMessage>
              data={SYSTEM_MESSAGES}
              renderItem={renderSystemMessage}
              keyExtractor={item => item.id}
              style={styles.list}
            />
          </View>
        </Animated.View>
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    backgroundColor: '#f0ffff',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    position: 'relative',
  },
  searchButton: {
    padding: 8,
    position: 'absolute',
    left: 16,
    zIndex: 1,
  },
  profileButton: {
    padding: 8,
    position: 'absolute',
    right: 16,
    zIndex: 1,
  },
  tabContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginHorizontal: 20,
    zIndex: 0,
    height: 44,
    paddingBottom: 2,
  },
  tabContainerWithoutSearch: {
    marginLeft: 8,
  },
  tab: {
    paddingHorizontal: 16,
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  activeTab: {
    borderBottomWidth: 2,
    borderBottomColor: '#26EBD7',
  },
  tabText: {
    fontSize: 16,
    color: '#666',
    textAlign: 'center',
    height: 22,
    lineHeight: 22,
  },
  activeTabText: {
    color: '#26EBD7',
    fontWeight: '500',
  },
  list: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  systemItem: {
    flexDirection: 'row',
    padding: 16,
    backgroundColor: 'white',
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#eee',
    alignItems: 'center',
  },
  iconContainer: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#26EBD7',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  messageInfo: {
    flex: 1,
  },
  title: {
    fontSize: 16,
    color: '#333',
    marginBottom: 4,
  },
  description: {
    fontSize: 14,
    color: '#999',
  },
  chatItem: {
    flexDirection: 'row',
    padding: 12,
    backgroundColor: 'white',
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#eee',
    alignItems: 'center',
  },
  avatar: {
    width: 45,
    height: 45,
    borderRadius: 22.5,
    marginRight: 12,
  },
  chatInfo: {
    flex: 1,
    height: 50,
    justifyContent: 'space-between',
  },
  topLine: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  name: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
    flex: 1,
    marginRight: 8,
  },
  time: {
    fontSize: 12,
    color: '#999',
  },
  bottomLine: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  lastMessage: {
    fontSize: 14,
    color: '#666',
    flex: 1,
    marginRight: 8,
  },
  unreadBadge: {
    backgroundColor: '#ff3b30',
    borderRadius: 10,
    minWidth: 18,
    height: 18,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 5,
  },
  unreadText: {
    color: 'white',
    fontSize: 11,
    fontWeight: '500',
  },
  searchWrapper: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 8,
    backgroundColor: '#f0ffff',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    marginTop: -1,
  },
  searchContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
    borderRadius: 20,
    paddingHorizontal: 12,
    height: 36,
    marginRight: 10,
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    marginLeft: 8,
    marginRight: 8,
    padding: 0,
    color: '#333',
  },
  cancelButton: {
    color: '#666',
    fontSize: 16,
    paddingVertical: 8,
    paddingHorizontal: 4,
  },
  tabSlider: {
    position: 'absolute',
    bottom: 0,
    left: 105,
    height: 2,
    backgroundColor: '#26EBD7',
  },
  contentContainer: {
    flex: 1,
    overflow: 'hidden',
  },
  slidingContent: {
    flexDirection: 'row',
    width: width * 2,
    flex: 1,
  },
  page: {
    width,
    flex: 1,
  },
});
